<?php


namespace app\api\controller;

use app\api\logic\OrderLogic;
use app\common\controller\BaseApiController;
use support\constants\LockKey;
use support\Log;
use support\Request;
use Throwable;
use Webman\Config;
use Webman\Http\Response;
use Yansongda\Pay\Pay;
use yzh52521\WebmanLock\Locker;

/**
 * 对外支付回调
 * Class NotifyController
 * @package app\api\controller
 */
class NotifyController extends BaseApiController
{
    protected $noNeedLogin = ['*'];

    public function alipayNotify(Request $request)
    {
        // 1. 获取配置文件 config/payment.php
        $config = Config::get('payment');

        // 2. 初始化配置
        Pay::config($config);

        // 3. 支付宝回调处理
        $result = Pay::alipay()->callback($request->post());
        Log::channel("pay")->info("订单回调:" . json_encode($request->post()));
        if ($result['trade_status'] === "TRADE_SUCCESS") {
            $key = LockKey::ORDER_ACTION . $result['out_trade_no'];
            $lock = Locker::lock($key);
            if (!$lock->acquire()) {
                return new Response(200, [], 'error');
            }
            try {
                $logic = new OrderLogic;
                $out_trade_no = $result['out_trade_no'];
                $trade_no = $result['trade_no'];
                $logic->transaction(function () use ($out_trade_no, $trade_no, $logic) {
                    $logic->payFinished($out_trade_no, $trade_no, 'alipay');
                });
            } catch (Throwable $exception) {
                Log::channel("pay")->error("回调发生异常:[" . $result['out_trade_no'] . "] 异常信息:" . $exception->getTraceAsString());
            } finally {
                $lock->release();
            }

        }
        return new Response(200, [], 'success');
    }
}